﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mimoza.Common;
using Mimoza.Transport;

namespace Mimoza.DBLayer.Transport.Client
{
    public class TransportDBLayer : Mimoza.Common.IDBLayer
    {
        public TransportDBLayer()
        {
            Common.RegistrationReply.RegisterInTransport();
        }

        public void Connect()
        {
        }

        public void ConnectToHostDB()
        { 
        }

        public void Connect(Connection conn)
        {
            m_dbContainers.Connection = conn;
            m_dbHostsRepository.Connection = conn;
            m_dbPoliciesRepository.Connection = conn;
            m_dbUpdatesRepository.Connection = conn;

            InitEventConnection(conn);
        }

        public void Disconnect()
        {
            m_connectionForEvent.Close();
        }

        public IDBContainerRepository DBContainerRepository
        {
            get
            {
                return m_dbContainers;
            }
        }

        public IDBHostRepository DBHostRepository
        {
            get
            {
                return m_dbHostsRepository;
            }
        }

        public IDBPolicyRepository DBPolicyRepository
        {
            get
            {
                return m_dbPoliciesRepository;
            }
        }

        public IDBUpdateRepository DBUpdateRepository
        {
            get
            {
                return m_dbUpdatesRepository;
            }
        }

        private void InitEventConnection(Connection conn)
        {
            m_connectionForEvent = new Connection(conn.RemoteAddress, conn.RemotePort);

            TransferObject reply;
            m_connectionForEvent.MakeRequest(new Common.RegistrationRequest(), out reply);

            Mimoza.Transport.Transport.Dispatcher.AddConnection(m_connectionForEvent);
        }

        DBContainers m_dbContainers = new DBContainers();
        HostsRepository m_dbHostsRepository = new HostsRepository();
        PoliciesRepository m_dbPoliciesRepository = new PoliciesRepository();
        UpdatesRepository m_dbUpdatesRepository = new UpdatesRepository();

        Connection m_connectionForEvent;
    }
}
